<script setup name="Conductivity">
import { ref, onMounted, nextTick, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { calculateConductivity, checkHealthStatus } from '@/api/product/mdtk'

const { t } = useI18n()
const router = useRouter()

// 响应式数据
const selectedElements = ref(['Mn', 'Zn']) // 默认选择Mn和Zn
const elementCompositions = ref({ Mn: 0.14, Zn: 1.14 }) // 默认成分值
const temperature = ref(373) // 默认温度为373K
const calcType = ref('both') // both/thermal/electrical
const isCalculating = ref(false)
const messageText = ref('')
const messageType = ref('')
const showResults = ref(false)
const thermalConductivity = ref('-')
const electricalConductivity = ref('-')
const similarData = ref([])
const similarityInfo = ref('')

// 可选元素列表 - 基于新HTML文件的元素
const availableElements = [
	'Li',
	'Al',
	'Si',
	'Ca',
	'Sc',
	'Mn',
	'Fe',
	'Ni',
	'Cu',
	'Zn',
	'Ga',
	'Sr',
	'Y',
	'Zr',
	'Ag',
	'Sn',
	'Sb',
	'La',
	'Ce',
	'Nd',
	'Sm',
	'Gd',
	'Er',
]

// 计算Mg含量
const mgContent = computed(() => {
	let total = 0
	Object.values(elementCompositions.value).forEach((value) => {
		if (!isNaN(value) && value >= 0) {
			total += value
		}
	})
	return Math.max(0, 100 - total)
})

// 检查Mg含量是否有效
const isMgContentValid = computed(() => {
	return mgContent.value >= 70
})

// 监听元素选择变化，更新成分对象
watch(
	selectedElements,
	(newElements, oldElements) => {
		// 移除未选择的元素
		Object.keys(elementCompositions.value).forEach((element) => {
			if (!newElements.includes(element)) {
				delete elementCompositions.value[element]
			}
		})

		// 添加新选择的元素
		newElements.forEach((element) => {
			if (!(element in elementCompositions.value)) {
				elementCompositions.value[element] = 0
			}
		})
	},
	{ deep: true }
)

// 获取元素的本地化名称
const getElementName = (element) => {
	return t(`conductivity.elements.${element}`, element)
}

// 显示消息函数
const showMessage = (messageKey, isError = false) => {
	messageText.value = t(messageKey)
	messageType.value = isError ? 'error' : 'success'

	// 3秒后自动清除消息
	setTimeout(() => {
		messageText.value = ''
		messageType.value = ''
	}, 3000)
}

// 选择元素
const selectElement = (element) => {
	const index = selectedElements.value.indexOf(element)
	if (index > -1) {
		// 取消选择
		selectedElements.value.splice(index, 1)
	} else {
		// 检查是否超过最大选择数量
		if (selectedElements.value.length >= 6) {
			showMessage('conductivity.messages.maxElements', true)
			return
		}
		// 选择元素
		selectedElements.value.push(element)
	}
}

// 更新元素成分值
const updateComposition = (element, value) => {
	elementCompositions.value[element] = parseFloat(value) || 0
}

// 计算函数
const calculateProperties = async () => {
	// 验证输入
	if (selectedElements.value.length === 0) {
		showMessage('conductivity.messages.selectElements', true)
		return
	}

	// 验证Mg含量
	if (!isMgContentValid.value) {
		showMessage('conductivity.messages.mgContentLow', true)
		return
	}

	// 收集成分数据
	const composition = {}
	let hasInvalidInput = false

	selectedElements.value.forEach((element) => {
		const value = elementCompositions.value[element] || 0

		if (isNaN(value) || value < 0) {
			hasInvalidInput = true
			return
		}

		if (value > 0) {
			composition[element] = value
		}
	})

	if (hasInvalidInput) {
		showMessage('conductivity.messages.invalidInput', true)
		return
	}

	if (
		isNaN(temperature.value) ||
		temperature.value < 273 ||
		temperature.value > 723
	) {
		showMessage('conductivity.messages.invalidTemperature', true)
		return
	}

	isCalculating.value = true

	try {
		// 准备请求参数
		const requestParams = {
			composition: composition,
			temperature: temperature.value,
			calculation_type: calcType.value,
		}

		// 使用封装的API接口
		const response = await calculateConductivity(requestParams)

		console.log(response)

		// 检查响应状态
		if (response) {
			const data = response

			// 显示结果
			if (data.thermal_conductivity !== undefined) {
				thermalConductivity.value = data.thermal_conductivity.toFixed(2)
			}
			if (data.electrical_conductivity !== undefined) {
				electricalConductivity.value = Math.round(data.electrical_conductivity)
			}

			similarData.value = data.similar_alloys || []
			similarityInfo.value = data.similarity_info || ''
			showResults.value = true

			// 滚动到结果区域
			await nextTick()
			const resultsElement = document.querySelector('.results-section')
			if (resultsElement) {
				resultsElement.scrollIntoView({
					behavior: 'smooth',
					block: 'start',
				})
			}

			showMessage('conductivity.messages.calculationComplete')
		} else {
			throw new Error(response.message || 'Calculation failed')
		}
	} catch (error) {
		console.error('Calculation error:', error)
		showMessage('conductivity.messages.calculationFailed', true)
	} finally {
		isCalculating.value = false
	}
}

// 检查后端服务状态
const checkBackendStatus = async () => {
	try {
		const response = await checkHealthStatus()

		if (response) {
			const data = response
			console.log('Backend status:', data)

			if (data.predictor_type === 'mock') {
				showMessage('conductivity.messages.mockMode')
			}
		}
	} catch (error) {
		console.error('Backend not available:', error)
		showMessage('conductivity.messages.serverUnavailable', true)
	}
}

onMounted(() => {
	nextTick(() => {})

	// 检查后端状态
	checkBackendStatus()
})
</script>

<template>
	<main class="conductivity-page">
		<div class="container">
			<!-- 页面标题 -->
			<div class="page-header">
				<h1 class="page-title">{{ t('conductivity.title') }}</h1>
				<p class="page-subtitle">
					{{ t('conductivity.subtitle') }}
				</p>
				<div class="title-divider"></div>
			</div>

			<div class="main-content">
				<!-- 输入参数卡片 -->
				<div class="card">
					<h2>
						<span>⚙️</span>
						<span>{{ t('conductivity.inputParams.title') }}</span>
					</h2>

					<!-- 元素选择模块 -->
					<div class="input-section">
						<div class="form-group">
							<label>{{
								t('conductivity.inputParams.elementSelection')
							}}</label>
							<div class="periodic-table">
								<!-- Mg元素 - 不可点击 -->
								<div class="element mg-element">Mg</div>
								<!-- 可选元素 -->
								<div
									v-for="element in availableElements"
									:key="element"
									class="element"
									:class="{ selected: selectedElements.includes(element) }"
									@click="selectElement(element)"
								>
									{{ element }}
								</div>
							</div>
						</div>

						<!-- Mg含量显示 -->
						<div class="form-group">
							<label>{{ t('conductivity.inputParams.mgContent') }}</label>
							<div
								class="mg-content-display"
								:class="{ error: !isMgContentValid }"
							>
								<span class="mg-label">{{
									t('conductivity.inputParams.mgLabel')
								}}</span>
								<span class="mg-value">{{ mgContent.toFixed(2) }}</span>
							</div>
							<small class="form-text text-muted">
								{{ t('conductivity.inputParams.mgDescription') }}
							</small>
							<div v-if="!isMgContentValid" class="error-message">
								{{
									t('conductivity.messages.mgContentError', {
										current: (100 - mgContent).toFixed(2),
									})
								}}
							</div>
						</div>

						<!-- 合金成分输入 -->
						<div v-if="selectedElements.length > 0" class="form-group">
							<label>{{ t('conductivity.inputParams.composition') }}</label>
							<div class="composition-input">
								<div
									v-for="element in selectedElements"
									:key="element"
									class="composition-item"
								>
									<input
										:id="`input-${element}`"
										type="number"
										:placeholder="`${element} %`"
										step="0.01"
										min="0"
										max="30"
										:value="elementCompositions[element] || 0"
										@input="updateComposition(element, $event.target.value)"
									/>
									<label>{{ getElementName(element) }}</label>
								</div>
							</div>
						</div>
					</div>

					<!-- 温度输入 -->
					<div class="temperature-section">
						<div class="form-group">
							<label>{{ t('conductivity.inputParams.temperature') }}</label>
							<input
								v-model.number="temperature"
								type="number"
								:placeholder="
									t('conductivity.inputParams.temperaturePlaceholder')
								"
								step="0.1"
								min="273"
								max="723"
							/>
						</div>
					</div>

					<!-- 消息显示区域 -->
					<div v-if="messageText" class="message-area">
						<div
							:class="
								messageType === 'error' ? 'error-message' : 'success-message'
							"
						>
							{{ messageText }}
						</div>
					</div>
				</div>

				<!-- 计算设置卡片 -->
				<div class="card">
					<h2>
						<span>🎯</span>
						<span>{{ t('conductivity.calcSettings.title') }}</span>
					</h2>

					<div class="form-group">
						<label>{{ t('conductivity.calcSettings.calcType') }}</label>
						<select v-model="calcType">
							<option value="both">
								{{ t('conductivity.calcSettings.calcTypes.both') }}
							</option>
							<option value="thermal">
								{{ t('conductivity.calcSettings.calcTypes.thermal') }}
							</option>
							<option value="electrical">
								{{ t('conductivity.calcSettings.calcTypes.electrical') }}
							</option>
						</select>
					</div>
					<button
						class="calculate-button"
						:disabled="isCalculating || !isMgContentValid"
						@click="calculateProperties"
					>
						<div class="loading-spinner" :class="{ show: isCalculating }"></div>
						🔬
						{{
							isCalculating
								? t('conductivity.button.calculating')
								: t('conductivity.button.calculate')
						}}
					</button>
					<div class="tips-section">
						<h4>💡 {{ t('conductivity.tips.title') }}</h4>
						<ul class="tips-list">
							<li v-html="t('conductivity.tips.tip1')"></li>
							<li v-html="t('conductivity.tips.tip2')"></li>
							<li v-html="t('conductivity.tips.tip3')"></li>
							<li v-html="t('conductivity.tips.tip4')"></li>
						</ul>
					</div>
				</div>
			</div>

			<!-- 结果展示区域 -->
			<div v-if="showResults" class="card results-section">
				<h2>
					<span>📊</span>
					<span>{{ t('conductivity.results.title') }}</span>
				</h2>

				<div class="results-grid">
					<div
						v-if="calcType === 'both' || calcType === 'thermal'"
						class="result-card"
					>
						<h3>{{ t('conductivity.results.thermalConductivity') }}</h3>
						<div class="result-value">{{ thermalConductivity }}</div>
						<div class="result-unit">
							{{ t('conductivity.results.thermalUnit') }}
						</div>
					</div>

					<div
						v-if="calcType === 'both' || calcType === 'electrical'"
						class="result-card"
					>
						<h3>{{ t('conductivity.results.electricalConductivity') }}</h3>
						<div class="result-value">{{ electricalConductivity }}</div>
						<div class="result-unit">
							{{ t('conductivity.results.electricalUnit') }}
						</div>
					</div>
				</div>

				<div v-if="similarData.length > 0" class="similar-data">
					<h3>📋 {{ t('conductivity.results.similarData') }}</h3>
					<div v-if="similarityInfo" class="similarity-info">
						{{ similarityInfo }}
					</div>
					<table class="data-table">
						<thead>
							<tr>
								<th>{{ t('conductivity.results.tableHeaders.no') }}</th>
								<th>
									{{ t('conductivity.results.tableHeaders.composition') }}
								</th>
								<th>
									{{ t('conductivity.results.tableHeaders.temperature') }}
								</th>
								<th v-if="calcType === 'both' || calcType === 'thermal'">
									{{ t('conductivity.results.tableHeaders.thermal') }}
								</th>
								<th v-if="calcType === 'both' || calcType === 'electrical'">
									{{ t('conductivity.results.tableHeaders.electrical') }}
								</th>
							</tr>
						</thead>
						<tbody>
							<tr v-for="(alloy, index) in similarData" :key="index">
								<td>{{ index + 1 }}</td>
								<td>
									{{ alloy['Formula [at.%]'] || alloy.composition || '-' }}
								</td>
								<td>
									{{
										alloy['T [K]']
											? parseInt(alloy['T [K]'])
											: alloy.temperature || '-'
									}}
								</td>
								<td v-if="calcType === 'both' || calcType === 'thermal'">
									{{
										alloy['λ [W·m-1·K-1]']
											? parseFloat(alloy['λ [W·m-1·K-1]']).toFixed(2)
											: alloy.thermal?.toFixed(2) || '-'
									}}
								</td>
								<td v-if="calcType === 'both' || calcType === 'electrical'">
									{{ alloy['σ [S·m-1]'] || alloy.electrical || '-' }}
								</td>
							</tr>
						</tbody>
					</table>
				</div>
			</div>
		</div>
	</main>
</template>

<style scoped lang="scss">
@import url('@/styles/content/index.scss');
@import url('@/styles/content/components/conductivity.scss');

.form-actions {
	display: flex;
	justify-content: space-between;
	gap: 1rem;
	margin: 1.5rem 0;

	.back-button,
	.reset-button {
		flex: 1;
		padding: 0.75rem 1.5rem;
		border: 2px solid var(--theme-accent);
		border-radius: 8px;
		background: transparent;
		color: var(--theme-accent);
		font-weight: 600;
		cursor: pointer;
		transition: all 0.3s ease;

		&:hover {
			background: var(--theme-accent);
			color: white;
			transform: translateY(-2px);
		}
	}

	.reset-button {
		border-color: var(--theme-warning);
		color: var(--theme-warning);

		&:hover {
			background: var(--theme-warning);
			color: white;
		}
	}
}
</style>
